var fs = require("fs");
var path = require("path");


module.exports = function (UC, source, config, ArFor, cache, package) {
    var UserControl = UC;


    var router = function (req, res, next) {
        var params = req.params;

        var etag = config.getETag(req.path);
        if (req.isConditionalGET()) {
            var _etag = req.getHeader('if-none-match');
            if (_etag == etag) {
                req.notModified()
                return
            }
        };

        res.etag_key = etag;

        new source({
            "SQL": "SELECT db.src FROM files AS db WHERE db.id={id}",
            "type": "row"
        }, {
            id: params.id
        }, function (db) {
            if (db && db.src) {
                var src = db.src;
                var localfile = path.join(config.Files.FileCache, src);
                fs.exists(localfile, function (exists) {
                    if (exists) {
                        res.setHeader('Cache-Control', "max-age=" + (60 * 60 * 24 * 30));
                        if (res.etag_key) {
                            res.setHeader('Etag', res.etag_key);
                        }
                        res.sendfile(localfile);
                    } else {
                        res.status(403).send("Sorry! You can't see that.");
                    }
                })
            } else {
                var value = {
                    error: 1
                };
                res.Json(value);
            }
        });
    }

    return router;
}